﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Objects;
using System.Data.Common;
using System.Data.SqlClient;

namespace MINERP.DAL.CustomerManage
{
    public class EditOrderDAL 
    {
        //属性
        public newSampleYPDBEntities DataEntites = new newSampleYPDBEntities();
        //string sqlCon = System.Configuration.ConfigurationManager.ConnectionStrings["fffff"].ToString();
        string sqlCon = DALBase.ConnStr;
        /// <summary>
        /// 获取实体实例
        /// </summary>
        /// <returns></returns>
        public newSampleYPDBEntities GetEntities()
        {
            newSampleYPDBEntities newEntities = DataEntites;
            return newEntities;
        }

        /// <summary>
        /// 获取产品的默认流程
        /// </summary>
        /// <param name="productID"></param>
        /// <returns></returns>
        public List<Tb_FlowTemplate> GetDefaultFlowsOfProduct(int productID)
        {
            try
            {
                ObjectQuery<Tb_FlowTemplate> query = DataEntites.Tb_FlowTemplate.Where("it.Tb_Product.ProuctId=" + productID).Include("tb_Tech");
                List<Tb_FlowTemplate> productTechs = new List<Tb_FlowTemplate>();
                foreach (Tb_FlowTemplate tech in query)
                {
                    productTechs.Add(tech);
                }
                return productTechs;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获得真实的产品流程
        /// </summary>
        /// <param name="inOrderProduct"></param>
        /// <returns></returns>
        public List<WorkOrderFlowList> GetRealFlow(int inOrderProduct)
        {
            try
            {
                List<WorkOrderFlowList> list = DataEntites.WorkOrderFlowList.Where(p => p.orderInfo.OrderProductId == inOrderProduct).ToList();
                return list;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取产品已分配的流程
        /// </summary>
        /// <returns></returns>
        public List<WorkOrderFlowList> GetProductTechs(int productID)
        {
            try
            {
                ObjectQuery<WorkOrderFlowList> query = DataEntites.WorkOrderFlowList.Where("it.orderInfo.OrderProductId=" + productID).Include("tb_Tech");
                List<WorkOrderFlowList> techs = new List<WorkOrderFlowList>();
                foreach (WorkOrderFlowList tech in query)
                {
                    techs.Add(tech);
                }
                return techs;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取产品已本地分配的流程
        /// </summary>
        /// <returns></returns>
        public List<WorkOrderFlowList> GetProductTechsLocal(int productID)
        {
            try
            {
                List<WorkOrderFlowList> query = DataEntites.WorkOrderFlowList.Where(p => p.orderInfo.OrderProductId == productID).ToList();
                return query;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取指定的流程
        /// </summary>
        /// <param name="flowID"></param>
        /// <returns></returns>
        public WorkOrderFlowList GetFlow(int flowID)
        {
            try
            {
                WorkOrderFlowList query = DataEntites.WorkOrderFlowList.Where("it.WorkFlowListId="+flowID).First();
                return query;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取所有纸型
        /// </summary>
        /// <returns></returns>
        public List<paperType> GetPaperType()
        {
            try
            {
                List<paperType> paperTypes = new List<paperType>();
                ObjectQuery<paperType> query = DataEntites.paperType;
                foreach (paperType pt in query)
                {
                    paperTypes.Add(pt);
                }
                return paperTypes;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取所有纸面
        /// </summary>
        /// <returns></returns>
        public List<paperFace> GetPaperFace()
        {
            try
            {
                List<paperFace> paperFaces = new List<paperFace>();
                ObjectQuery<paperFace> query = DataEntites.paperFace;
                foreach (paperFace pf in query)
                {
                    paperFaces.Add(pf);
                }
                return paperFaces;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取指定订单包下的所有产品
        /// </summary>
        /// <param name="orderID"></param>
        /// <returns></returns>
        public List<orderInfo> GetOrderInfoByOrderID(int orderID)
        {
            try
            {
                ObjectQuery<orderInfo> query = DataEntites.orderInfo.Where("it.Tb_OrderBag.OrderBagId=" + orderID).Include("Tb_Product");
                List<orderInfo> ListProduct = new List<orderInfo>();
                foreach (orderInfo product in query)
                {
                    ListProduct.Add(product);
                }
                return ListProduct;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region 获取产品的类型码
        /// <summary>
        /// 获取产品的类型码 1需要设计的产品 2不需要设计的产品 3需要指定尺寸的扩印产品 4直接扩印的产品
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public int GetProductTypeCode(int productId)
        {
            try
            {
                Tb_Product product = DataEntites.Tb_Product.Where("it.ProuctId=" + productId).Include("tb_ProductType").First();
                int productTypeCode = product.tb_ProductType.ProductTypeCode;
                return productTypeCode;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        /// <summary>
        /// 获取订单包的头信息
        /// </summary>
        /// <param name="orderID"></param>
        /// <returns></returns>
        public Tb_OrderBag GetOrderBagTitle(int orderID)
        {
            try
            {
                Tb_OrderBag query = DataEntites.Tb_OrderBag.Where("it.OrderBagId=" + orderID).Include("Shop").First();
                return query;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取指定产品的纸型ID，纸面ID
        /// </summary>
        /// <param name="productID"></param>
        /// <param name="paperTypeID"></param>
        /// <param name="PaperFaceID"></param>
        public List<int> GetPaperTypeAndPaperFaceForProduct(int productID)
        {
            try
            {
                string esql1 = "select max(it.paperType.paperTypeID) as paperTypeID,max(it.paperFace.paperFaceId) as paperFaceID from photoInfo as it where it.orderInfo.OrderProductId=" + productID;
                ObjectQuery<DbDataRecord> query = DataEntites.CreateQuery<DbDataRecord>(esql1);
               
                List<int> ids = new List<int>();
                foreach (DbDataRecord record in query)
                {
                    if ( record["paperTypeID"]!= DBNull.Value)
                    {
                    
                    ids.Add(Convert.ToInt32(record["paperTypeID"]));
                }
                    else
                    {
                        ids.Add(DataEntites.paperType.FirstOrDefault().PaperTypeID);
                    }
                    if (record["paperFaceID"] != DBNull.Value)
                    {
                        ids.Add(Convert.ToInt32(record["paperFaceID"]));
                    }
                    else
                    {
                        ids.Add(DataEntites.paperFace.FirstOrDefault().PaperFaceID);
                    }
                    break;
                }
                return ids;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取产品的头信息
        /// </summary>
        /// <param name="orderProductID">订单内产品ID</param>
        /// <returns></returns> 
        public orderInfo GetOrderInfoTitle(int orderProductID)
        {
            try
            {
                orderInfo product = DataEntites.orderInfo.Where("it.OrderProductId=" + orderProductID).First();
                return product;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取产品内的照片集合 
        /// </summary>
        /// <param name="orderproductID"></param>
        /// <returns></returns>
        public List<photoInfo> GetPhotosInOrderInfo(int orderproductID)
        {
            try
            {
                ObjectQuery<photoInfo> query = DataEntites.photoInfo.Where("it.orderInfo.OrderProductId=" + orderproductID);
                List<photoInfo> ListPhoto = new List<photoInfo>();
                foreach (photoInfo photo in query)
                {
                    ListPhoto.Add(photo);
                }
                return ListPhoto;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 根据订单包ID获取订单包
        /// </summary>
        /// <param name="orderID"></param>
        /// <returns></returns>
        public Tb_OrderBag GetOrderBagByOrderID(int orderID)
        {
            try
            {
                Tb_OrderBag orderBag = DataEntites.Tb_OrderBag.Where("it.OrderBagId=" + orderID).First();
                return orderBag;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 根据商户ID获取商户
        /// </summary>
        /// <param name="shopID"></param>
        /// <returns></returns>
        public Shop GetShopByShopID(int shopID)
        {
            try
            {
                Shop shop = DataEntites.Shop.Where("it.shopId=" + shopID).First();
                return shop;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取当前订单包内已有的最大的照片编号
        /// </summary>
        /// <param name="orderID"></param>
        /// <returns></returns>
        public string GetMaxXuHaoInOrder(int orderID)
        {
            try
            {
                //string esql = "select value it.PhotoName from photoInfo as it where it.orderInfo.Tb_OrderBag.OrderBagId=" + orderID + " order by it.photoName desc";
                
                //string xuhao = DataEntites.CreateQuery<string>(esql).First();
                //return xuhao;
               photoInfo listPhoto=
                    DataEntites.photoInfo.Where(p => p.orderInfo.Tb_OrderBag.OrderBagId == orderID).OrderByDescending(
                        p => p.photoName).FirstOrDefault();
               if(listPhoto==null)
               {
                   return "";//无照片的产品
               }
               else
               {
                   return listPhoto.photoName;
               }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取指定的产品
        /// </summary>
        /// <param name="orderProductID"></param>
        /// <returns></returns>
        public orderInfo GetProductByOrderProductID(int orderProductID)
        {
            try
            {
                orderInfo product = DataEntites.orderInfo.Include("WorkOrderFlowList").Where("it.OrderProductId=" + orderProductID).First();
                return product;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取一个产品内所有的照片集合
        /// </summary>
        /// <param name="productID"></param>
        /// <returns></returns>
        public List<photoInfo> GetPhotoInfoInProduct(int productID)
        {
            try
            {
                ObjectQuery<photoInfo> query = DataEntites.photoInfo.Where("it.orderInfo.OrderProductId=" + productID);   //试试订单包ID能否取得数据
                List<photoInfo> ListPhoto = new List<photoInfo>();
                foreach (photoInfo photo in query)
                {
                    ListPhoto.Add(photo);
                }
                return ListPhoto;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public photoInfo GetPhotoInfoByPhotoID(int photoID)
        {
            try
            {
                photoInfo photo = DataEntites.photoInfo.Where("it.photoID=" + photoID).First();
                return photo;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region 获取一个产品内所有照片的详情
        /// <summary>
        /// 获取一个产品内所有照片的详情
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public List<photoInfo> GetPhotosInOrderInfoXQ(int orderProductId)
        {
            try
            {
                ObjectQuery<photoInfo> query = DataEntites.photoInfo.Where("it.orderInfo.OrderProductId=" + orderProductId);
                List<photoInfo> ListPhoto = new List<photoInfo>();
                foreach (photoInfo photo in query)
                {
                    ListPhoto.Add(photo);
                }
                return ListPhoto;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 根据productId获取产品模板
        /// <summary>
        /// 根据productId获取产品模板
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public Tb_Product GetProductByProductID(int productId)
        {
            try
            {
                Tb_Product product = DataEntites.Tb_Product.Where(p => p.ProuctId == productId).FirstOrDefault();
                return product;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 根据TechId获取节点
        /// <summary>
        /// 根据TechId获取节点
        /// </summary>
        /// <param name="techId"></param>
        /// <returns></returns>
        public tb_Tech GetTechByTechID(int techId)
        {
            try
            {
                tb_Tech tech = DataEntites.tb_Tech.Where(p => p.TechId == techId).FirstOrDefault();
                return tech;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion 

        #region 订单在服务器上的存放总路径
        /// <summary>
        /// 订单在服务器上的存放总路径
        /// </summary>
        /// <returns></returns>
        public string GetOrderStorePath()
        {
            try
            {
                FileDirPath fd = DataEntites.FileDirPath.Where(p => p.id == 2).First();
                string orderStorePath = fd.FileDir;
                return orderStorePath;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取订单下任一产品的路径
        /// <summary>
        /// 获取订单下任一产品的路径
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public string GetAOrderInfoPathInOrder(int orderId)
        {
            try
            {
                orderInfo info = DataEntites.orderInfo.Where(p => p.Tb_OrderBag.OrderBagId == orderId).FirstOrDefault();
                return info.OrderPath;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取指定产品的路径
        /// <summary>
        /// 获取指定产品的路径
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public string GetOrderInfoPathByOrderProductId(int orderProductId)
        {
            try
            {
                orderInfo info = DataEntites.orderInfo.Where(p => p.OrderProductId == orderProductId).FirstOrDefault();
                return info.OrderPath;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public string GetOrderInfoPathByOrderProductId2(int orderProductId)
        {
            try
            {
                photoInfo photo = DataEntites.photoInfo.Where(p => p.orderInfo.OrderProductId == orderProductId).First();
                string photoPath = photo.OldPicPath;
                return photoPath.Substring(0, photoPath.LastIndexOf("\\"));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取照片已开单路径
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public string GetOpenedOrderInfoPath(int orderProductId)
        {
            try
            {
                photoInfo photo = DataEntites.photoInfo.Where(p => p.orderInfo.OrderProductId == orderProductId).First();
                string photoPath = photo.picPath;
                return photoPath.Substring(0, photoPath.LastIndexOf("\\"));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取产品里的照片
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public photoInfo GetPhotoInOrderInfo(int orderProductId)
        {
            try
            {

                photoInfo photo = DataEntites.photoInfo.Where(p => p.orderInfo.OrderProductId == orderProductId).FirstOrDefault();
                return photo;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取指定产品的当前节点的上一个节点
        /// <summary>
        /// 获取指定产品的当前节点ID
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public int GetOrderProductCurrentTech(int orderProductId)
        {
            try
            {
                int status = (int)COM.OrderFlowListStatus.Useable;
                int status2 = (int)COM.OrderFlowListStatus.UseableAccept;
                WorkOrderFlowList CurrentTech = DataEntites.WorkOrderFlowList.Where(p => p.orderInfo.OrderProductId == orderProductId && (p.Status == status || p.Status == status2)).FirstOrDefault();
                if (CurrentTech == null)
                    return -1;
                //取当前节点的上一个节点
                string esql="select value max(it.WorkOrder) from WorkOrderFlowList as it where it.orderInfo.OrderProductId="+orderProductId+" and it.WorkOrder<"+CurrentTech.WorkOrder;
                int workOrder=DataEntites.CreateQuery<int>(esql).First();
                WorkOrderFlowList preTech = DataEntites.WorkOrderFlowList.Where(p => p.orderInfo.OrderProductId == orderProductId && p.WorkOrder == workOrder).First();
                if (!preTech.tb_TechReference.IsLoaded)
                    preTech.tb_TechReference.Load();
                return preTech.tb_Tech.TechId;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 指定的流程是否存在于指定的产品模板流程中
        /// <summary>
        /// 指定的流程是否存在于指定的产品模板流程中
        /// </summary>
        /// <param name="techId"></param>
        /// <param name="productId"></param>
        /// <returns></returns>
        public bool IsTechExist(int techId, int productId)
        {
            try
            {
                //string esql = "select value count(it.FlowTemplateId) from Tb_FlowTemplate as it where it.Tb_Product.ProuctId=" + productId + " and it.tb_Tech.TechId=" + techId;
                List<Tb_FlowTemplate> flows = DataEntites.Tb_FlowTemplate.Include("tb_Tech").Where(p => p.Tb_Product.ProuctId == productId).ToList();
                
                Tb_FlowTemplate flow = flows.Find(p => p.tb_Tech.TechId == techId);
                if (flow == null)
                    return false;
                bool isWorkOrderMax=true;          //workOrder是否是最大
                foreach (Tb_FlowTemplate f in flows)
                {
                    if (f.WorkOrder > flow.WorkOrder)
                    {
                        isWorkOrderMax = false;
                        break;
                    }
                }
                if (isWorkOrderMax == true)
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion


        #region 取得产品的委外记录
        /// <summary>
        /// 取得产品的委外记录
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public OutProcessRecord GetOutShopRecord(int orderProductId)
        {
            try
            {
                OutProcessRecord record = null;
                record = DataEntites.OutProcessRecord.Where(p => p.orderInfo.OrderProductId == orderProductId).FirstOrDefault();
                return record;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 根据outShopId取得委外商
        /// <summary>
        /// 根据outShopId取得委外商
        /// </summary>
        /// <param name="outShopId"></param>
        /// <returns></returns>
        public OutProcessShop GetOutShopByOutShopId(int outShopId)
        {
            try
            {
                return DataEntites.OutProcessShop.Where(p => p.OutShopId == outShopId).First();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        
        #region 根据orderProductId取得对应的orderInfo
        /// <summary>
        /// 根据orderProductId取得对应的orderInfo
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public orderInfo GetOrderInfoByOrderProductId(int orderProductId)
        {
            try
            {
                return DataEntites.orderInfo.Where(p => p.OrderProductId == orderProductId).First();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 根据userId获取用户
        /// <summary>
        /// 根据userId获取用户
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public users GetUserByUserId(int userId)
        {
            try
            {
                users u = DataEntites.users.Where(p => p.userID == userId).FirstOrDefault();
                return u;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        /// <summary>
        /// 删除对象
        /// </summary>
        /// <param name="entity"></param>
        public void Delete(object entity)
        {
            DataEntites.DeleteObject(entity);
        }

        public List<CommonChargeItem> GetAllCostItems()
        {
            try
            {
             
                List<CommonChargeItem> itemList = DataEntites.CommonChargeItem.ToList();
                return itemList;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        //public EntityCollection<CommonChargeItem>() GetItemsByOrder(orderInfo inOrder)
        //{
        //    inOrder.CommonChargeItem.Load();
        //    if (inOrder.CommonChargeItem.Count == 0)
        //    {
        //        return DataEntites.;

        //    }
        //    else
        //    {
        //        return inOrder.CommonChargeItem;
        //    }

        //}
        /// <summary>
        /// 保存修改
        /// </summary>
        public void SaveData()
        {
            DataEntites.SaveChanges();
        }

        #region 是否存在还未移动完的照片
        /// <summary>
        /// 是否存在还未移动完的照片
        /// </summary>
        public bool PhotoMoveCompleted(int orderBagId)
        {
            SqlConnection con = new SqlConnection(sqlCon);
            try
            {
                int status1 = (int)COM.PhotoStatus.WaitPhotoMove;
                int status2 = (int)COM.PhotoStatus.PhotoNotExist;
                int status3 = (int)COM.PhotoStatus.PhotoBingFa;
                string statusStr = status1.ToString() + "," + status2.ToString() + "," + status3.ToString();
                string sql = "select count(photoId) from photoInfo,orderInfo where orderbagid=" + orderBagId + " and photoInfo.orderproductid=orderinfo.orderproductid and photoinfo.status in (" + statusStr + ")";
                SqlCommand cmd = new SqlCommand(sql, con);
                con.Open();
                int r = Convert.ToInt32(cmd.ExecuteScalar());
                if (r > 0)
                    return false;
                else
                    return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
            }
        }
        #endregion

        //----------------------------------------------------------
        //----------------修改产品类型------------------------------
        //----------------------------------------------------------
        #region 获取所有的流程节点
        /// <summary>
        /// 获取所有的流程节点
        /// </summary>
        /// <returns></returns>
        public List<tb_Tech> GetAllTech()
        {
            try
            {
                return DataEntites.tb_Tech.ToList(); 
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
    }
}
